import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import useStore from '@/store'
import router from '@/router'

// declare module 'axios' {
//   export interface AxiosRequestConfig {

//   }
// }

// const baseURL = 'http://pcapi-xiaotuxian-front-devtest.itheima.net/'
const http = axios.create({
  baseURL: '/api',
  timeout: 5000
})

// 请求拦截
http.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 1.获取用户信息对象
    const { user } = useStore()
    // 2.判断是否有token
    if (user.user.token) {
      // 设置token
      typeof config.headers.set === 'function' &&
        config.headers.set('Authorization', `Bearer ${user.user.token}`)
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// 响应拦截
// res => res.data 直接拿到后台数据
http.interceptors.response.use(
  (res: AxiosResponse) => res,
  err => {
    // 401状态码 进入改函数
    if (err.response && err.response.status === 401) {
      // 1.清空无效用户信息
      // 2.跳转到登录页并携带当前路由参数地址
      const { user } = useStore()

      user.$reset()

      // 设置当前路由地址
      const fullPath = encodeURIComponent(router.currentRoute.value.fullPath)
      router.push(`/login?redirectUrl=${fullPath}`)
    }
  }
)

export default http
